package ch.ethz.fcl.metrobuzz;

import java.awt.BorderLayout;
import java.awt.Canvas;

import javax.swing.JFrame;

import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GL11;

import ch.ethz.fcl.metrobuzz.controller.MBController;
import ch.ethz.fcl.metrobuzz.data.MBData;
import ch.ethz.fcl.metrobuzz.data.loader.plan.SingaporeTransitPlanFileLoader;
import ch.ethz.fcl.metrobuzz.render.MBRenderer;
import ch.ethz.fcl.metrobuzz.viewer.MBViewer;
import ch.ethz.fcl.metrobuzz.viewer.MBViewer.ProjectionType;

public final class MetroBuzz {
	private int screenWidth = 7680;
	private int screenHeight = 4320;
	private MBContainer container;
	private JFrame frame;

	public static void main(String[] args) {
		new MetroBuzz(args).run();
	}

	public MetroBuzz(String[] args) {
		init(args);
	}

	private void run() {
		while (!Display.isCloseRequested()) {
			GL11.glPushMatrix();
			container.getViewer().update();
			if (MBViewer.newUpdate)
				container.getRender().render();
			GL11.glPopMatrix();

			container.getControl().update();

			Display.update();
			Display.sync(60);
		}
	}

	private void init(String[] args) {
		if (args.length == 0) {
			System.out.println("please specify data base path on command line");
			System.exit(0);
		}

		container = new MBContainer();

		MBData data = new MBData(container);

		new SingaporeTransitPlanFileLoader().load(data, args[0]); // load data
		data.init();

		new MBRenderer(container);

		MBViewer view = new MBViewer(ProjectionType.Perspective, container);
		new MBController(container);

		setDisplay();
		view.getCamera().setDistance(1.5f);
	}

	private void setDisplay() {
		screenWidth = Display.getDesktopDisplayMode().getWidth();
		screenHeight = Display.getDesktopDisplayMode().getHeight();

		frame = new JFrame();

		Canvas canvas = new Canvas();
		canvas.setSize(screenWidth * 4 / 5, screenHeight);

		try {
			Display.setParent(canvas);
		} catch (LWJGLException e1) {
			e1.printStackTrace();
		}

		// add control panel and canvas to frame
		// frame.add(container.getControl().getControlPanel());
		frame.add(canvas, BorderLayout.WEST);

		frame.pack();
		frame.setSize(screenWidth, screenHeight);
		frame.setVisible(true);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
}
